import cn from 'classnames';
import PropTypes from 'prop-types';
import React from 'react';
import { Link } from 'react-router-dom';
import { withRouter } from 'react-router';
import s from './style.module.css';
import AddYunaqBlacklist from '../../../../../../components/AddYunaqBlacklist';
import Label from '../../../../../../components/Label';
import { datetime } from '../../../../../../../common/formatter';
import fetch from 'API/fetch';
import { CONTENT_IDX_LABEL_MAP } from '../../../../../../../common/constants';
import Icon from '../../../../../Home/icon';
import Breadcrumb, { Item } from '../../../../../../components/Breadcrumb';
import Loading from '@knownsec/react-component/dist/Loading';
import Anchor from '@knownsec/react-component/dist/Anchor';
const { Link: ALink } = Anchor;
const levelMap = {
  5: '严重',
  4: '高危',
  3: '中危',
  2: '低危',
  1: '低危',
  0: '低危'
}
const reasonMap = {
	1: '暂不关注',
	2: '误报',
	3: '其他'
}
function DetailC({
	className,
	location,
	location: { sendState },
	match: {
		params: { taskId },
	},
}) {
	sendState && sessionStorage.setItem('state', JSON.stringify(sendState));
	const state = JSON.parse(sessionStorage.state);
	const [data, setData] = React.useState({ results: [] });
	const [hasDetails, setHasDetails] = React.useState(null);
	const [loading, setLoading] = React.useState(false);
	const getDate = async () => {
		setLoading(true);
		const isIgnore = location.pathname.includes('/policy-manage/ignore-risk-detail')
		const res = await fetch(
			isIgnore ? `/api/v2/tasks/warning/ignore?warning_id=${state.warning_id}` : `/api/v2/tasks/content/evidence?id=${state.taskId}&warningId=${state.id}`,
			{
				method: 'GET',
			}
		);
		if (res.code === 200) {
			const data_ = JSON.parse(JSON.stringify(res?.data) || null) || {}
			delete data_.detail
			const results = isIgnore ? {...res?.data?.detail, ...data_, isIgnore} : res.results;
			setData(results);
			codeDetails(results);
		}
		setLoading(false);
	};
	// 详情表 data.detail为老数据处理
	const tbodyContent = () => {
		const showText = (type, td, e) => {
			if (data.detail) {
				const obj = {
					敏感词: {
						td1: CONTENT_IDX_LABEL_MAP.keyword[e[0]],
						td2: e[1].join(','),
					},
					隐私信息: {
						td1: CONTENT_IDX_LABEL_MAP.privacy_disclosure[e[0]],
						td2: e[1],
					},
				};
				return obj[type][td];
			} else {
				const obj = {
					敏感词: {
						td1:
							CONTENT_IDX_LABEL_MAP.keyword[e.category] ||
							CONTENT_IDX_LABEL_MAP.keyword[e.type],
						td2: e.word ? e.word : e.keywords ? e.keywords.join(',') : '',
					},
					隐私信息: {
						td1: CONTENT_IDX_LABEL_MAP.privacy_disclosure[e.type],
						td2: e.content,
					},
				};
				return obj[type][td];
			}
		};
		let det = [];
		if (!data.results[0] && !data.detail) {
			return (
				<tbody>
					<tr className={s.row}>
						<td className={s.td1} colSpan="2">
							暂无数据
						</td>
					</tr>
				</tbody>
			);
		} else if (data.detail) {
			det = Object.entries(data.detail);
		} else {
			det = data.results;
		}
		return (
			<tbody>
				{det.map((e, i) => {
					return (
						<tr className={s.row} key={i}>
							<td className={s.td1}>{showText(state.title, 'td1', e)}</td>
							<td className={s.td2}>{showText(state.title, 'td2', e)}</td>
						</tr>
					);
				})}
			</tbody>
		);
	};
	// 源码显示
	const codeDetails = data => {
		const style = { color: '#fff', background: '#e70c0c' };
		let str = '';
		const dom = [];

		if (!data.results) {
			setHasDetails(null);
		}
		Object.values(data.results).forEach(item => {
			if (!item.evidences) {
				return false;
			}
			item.evidences.forEach(code => {
				str = code.split(item.word || item.content);
				dom.push(
					<p className={s.codeRow}>
						{str.map((e, i) => {
							if (i < str.length - 1) {
								return (
									<>
										<span>{e}</span>
										<span style={style}>{item.word || item.content}</span>
									</>
								);
							} else {
								return (
									<>
										<span>{e}</span>
										<p>......</p>
									</>
								);
							}
						})}
					</p>
				);
			});
		});

		if (dom[0]) {
			setHasDetails(
				<div>
					{dom.map(e => {
						return e;
					})}
				</div>
			);
		} else {
			setHasDetails(null);
		}
	};
	const bread = () => {
		if (location.pathname.includes('/asset-manage/manage/web')) {
			return (
				<Breadcrumb>
					<Item disabled key="asset-manage">
						资产管理
					</Item>
					<Item key="manage/web">Web资产</Item>
					<Item key="Detail">详情</Item>
					<Item>威胁详情</Item>
				</Breadcrumb>
			);
		} else if (location.pathname.includes('/policy-manage/ignore-risk-detail')) {
			return <Breadcrumb>
				<Item disabled key="policy-manage">
					综合管理
				</Item>
				<Item key="ignore-risk-manage">已忽略威胁</Item>
				<Item>威胁详情</Item>
			</Breadcrumb>
		} else {
			return (
				<Breadcrumb>
					<Item key="job-manage" disabled>
						任务管理
					</Item>
					<Item key="web-task">Web安全监测</Item>
					<Item
							key={`detail?id=${state.atid}&type=${state.taskType}&tag=content`}
						>
							监测结果
						</Item>
					{state.isHistory && (
						<Item
							key={`history?asset_task_id=${state.atid}&task_id=${state.taskId}&task_types=content`}
						>
							历史任务
						</Item>
					)}
					<Item key="">威胁详情</Item>
				</Breadcrumb>
			);
		}
	};
	React.useMemo(() => {
		getDate();
	}, []);
	return (
		<div className={cn(className, s.detail)}>
			{bread()}
			<Loading show={loading} label="" />
			<div className={s.content}>
				<div>
					<div className={s.cydEnabled}>
						{state.cydEnabled && (
							<AddYunaqBlacklist
								size="small"
								taskId={state.taskId}
								warningId={state.id}
							/>
						)}
					</div>
					<div className={s.content1} style={{ padding: '1.5rem 1.5rem 0 1.5rem'}}>
						<Label className={s.labelDetail}>威胁详情</Label>
						<div className={cn('df aic pl10 pr10')}>
							<span className={'flex1'}>威胁名称：{data?.title}</span>
							<span className={'flex1'}>威胁等级：{levelMap[data?.level] || '- -'}</span>
							<span className={'flex1'}>发现时间：{datetime(data?.foundAt)}</span>
						</div>
						{data?.isIgnore && <div className={cn('df aic pl10 pr10 mt10')}>
							<span className={'flex1'}>
								忽略时间：{datetime(data?.ignored_time) || '暂无'}
							</span>
							<span className={'flex2'}>忽略原因：{reasonMap[data?.reason?.type]}</span>
						</div>}
					</div>
				</div>
				<div className={cn('df aifs pr mt24 flex1', s.vdBox)}>
					<Anchor
						className={s.anchoritem}
						onClick={e => e.preventDefault()}
						getContainer={() => document.getElementById('vd')}
					>
						<ALink href="#affects" title="风险地址" />
						<ALink href="#title" title={state.title} />
						<ALink href="#detail" title="风险地址源码" />
					</Anchor>
					<div id='vd' className={cn(s.vd, 'pl10 pr10')}>
						<div id="affects">
							<Label className={cn('mb10 mt20')}>风险地址：</Label>
							<div className={s.p0_5}>{state.url || '暂无数据'}</div>
						</div>
						<div id="title">
							<Label className={cn('mb10 mt20')}>{state.title}：</Label>
							<div className={s.p0_5}>
								<div className={s.tableBox}>
									<table className={s.table}>
										<thead>
											<tr className={s.head}>
												<td className={s.td1}>{state.title}类型</td>
												<td className={s.td2}>详情</td>
											</tr>
										</thead>
										{tbodyContent()}
									</table>
								</div>
							</div>
						</div>
						<div id='detail'>
							<div className={s.content1}>
								<Label className={cn('mb10 mt20')}>风险地址源码</Label>
								<div>
									<span className={s.titleSpan}>抓取时间：</span>
									<span>
										{data && hasDetails !== null
											? datetime(data.foundAt) || '- -'
											: '- -'}
									</span>
								</div>
								<div className={cn(s.showBox, 'ml10 mr10')}>
									{hasDetails || (
										<div className={cn(s.empty)}>
											<Icon active="empty"></Icon>
											<span>暂无数据</span>
										</div>
									)}
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	);
}

DetailC.propTypes = {
	className: PropTypes.string,
	history: PropTypes.shape({
		push: PropTypes.func.isRequired,
	}).isRequired,
	location: PropTypes.any,
	match: PropTypes.shape({
		sendState: PropTypes.any,
		params: PropTypes.shape({
			taskId: PropTypes.string.isRequired,
		}).isRequired,
	}).isRequired,
	params: PropTypes.any,
};
DetailC.defaultProps = {
	className: '',
};

export default withRouter(DetailC);
